package com.cqwu.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @author LK
 * @time  2015-12-7 下午2:40:44
 * 解析Xml文件 ,传入keyvalue.xml 文件中的每个节点的id值或者name值返回一个map集合
 * 
 */
public class XMLUtil {
	
	public static Document getDocument() throws Exception{
		SAXReader reader = new SAXReader();                 
	    Document   document = reader.read(new File("src/keyvalue.xml")); 
	    return document;
	}
	
	/**
	 * @param  xml 文件中节点的id号或者name值进行查询
	 * @return 返回一个key/value的Map 方便jsp中标签进行迭代
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> getXMLValue(String idOrName){
		Map<String, String> map = new HashMap<String, String>();
		try {
			Document document = getDocument();
			Element root = document.getRootElement();  
			for(Iterator<Element> it = root.elementIterator();it.hasNext();){
				Element el = (Element) it.next();
				if(el.attribute("id").getData().equals(idOrName) || el.attribute("name").getData().equals(idOrName)){
					for(Iterator<Element> iter = el.elementIterator();iter.hasNext();){
						Element childElement = (Element) iter.next();
						map.put(childElement.attribute("key").getText(), childElement.getText());
					}
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/*
	public static void main(String[] args) throws Exception {
		Map<String, String> map =  getXMLValue("2");
		System.out.println(map.get("3"));
	}*/
	
}
